import {
    getActiveFileAndLineText
}
from './utils';

const hx = require('hbuilderx');
const path = require('path');
const fs = require('fs');

async function generate(param) {
    void param;

    const lineInfo = await getActiveFileAndLineText();

    const result = /\[(.*)\]\s*\((.*)\)/.exec(lineInfo[1]);
    if (result && result.length > 2) {
        if(/!\[(.*)\]\s*\((.*)\)/.test(lineInfo[1])){
            let btn = await hx.window.showMessageBox({
                type: 'warning',
                title: '警告',
                text: '生成的文件可能是图片是否需要继续生成？',
                buttons: ['确定', '取消']
            });
            if(btn !== "确定"){
                return;
            }
        }
        
        const title = result[1];
        const filePath = result[2];

        const targetFilePath = path.resolve(path.dirname(lineInfo[0]), filePath);

        if (fs.existsSync(targetFilePath)) {
            hx.window.setStatusBarMessage('目标文件已经存在', 3000, 'warn');
            return
        }

        const targetDir = path.dirname(targetFilePath);
        if (!fs.existsSync()) {
            fs.mkdirSync(targetDir, {
                recursive: true
            });
        }

        const targetFileText = `# ${title}`;

        fs.writeFileSync(targetFilePath, targetFileText);
        hx.window.setStatusBarMessage('目标文件生成成功', 3000, 'info');
        
        hx.workspace.openTextDocument(targetFilePath);
    }
}

export {
    generate
}